## main driving script for XDS

diary xds.log ; diary on
printf("+++ XDS started at %s +++\n", datestr(now, 31)) ;

if strcmp(program_invocation_name, "xds.m")
   A = argv ;
else
   A = {} ;
endif

addpath([pwd "/fun"]) ;
addpath([pwd "/util"]) ;
Lptr = Lpdd = Lcal = Lout = Lplt = true ;

for i = 1:numel(A)
   if exist(A{i}, "file")
      A{i} = ["CFG = \"" A{i} "\";"] ;
   elseif regexp(A{i}, "^[01]{5}$")
      [Lptr Lpdd Lcal Lout Lplt] = deal(cellfun(@(x) x == "1", num2cell(A{i}), "UniformOutput", false){:}) ;
      A{i} = {} ;
   endif
endfor

## calibration
init(A{:}, "SIM = \"\";") ;      # initialization
ptr(Lptr)  ;	                 # process atmospheric predictor fields
pdd(Lpdd)  ;                     # process predictands (stations)
cal(Lcal)  ;                     # calibration
out(Lout)  ;                     # downscaled analyses

## simulation
init(A{:}) ;                     # initialization
ptr(Lout & Lptr)  ;	         # process atmospheric predictor fields
out(Lout)  ;                     # downscaled GCMs

plt(Lplt)  ;                     # simple plots for checking

printf("+++ XDS ended at %s +++\n", datestr(now, 31)) ;
diary off
